<!--
 * @Descripttion: 项目报名详情/添加
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-10-14 09:12
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-13 10:08:36
-->
<template>
	<div class="page-box">
		<h2 class="page-box-title">项目详情</h2>
		<div class="page-box-content">
			<h3>项目基本信息</h3>
			<el-form class="page-box-content-block form-space" :label-position="labelPosition" label-width="160px"
				size="mini">
				<el-row>
					<el-col :span="12">
						<el-form-item label="项目名称:">{{baseInfo.projectName}}</el-form-item>
						<el-form-item label="询价开始时间:">{{baseInfo.startTime|formeTime}}</el-form-item>
						<el-form-item label="项目状态:"
							style="color: blue; font-size: 24px;">{{baseInfo.projectStateName}}</el-form-item>
						<el-form-item label="总预算（元）:">{{baseInfo.sumBudgetStr}}</el-form-item>
						<el-form-item label="公告发布时间:">{{baseInfo.createTime|formeTime}}</el-form-item>
						<el-form-item v-if="baseInfo.projectState === '00026_0'" label="距离询价开始倒计时:"
							style="color: red; font-size: 24px;">{{countdown >= 0 ? strCountdown : '已结束'}}</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="项目编码:">{{baseInfo.projectNo}}</el-form-item>
						<el-form-item label="询价结束时间:">{{baseInfo.endTime|formeTime}}</el-form-item>
						<el-form-item label="定标状态:">{{baseInfo.picketageStateName}}</el-form-item>
						<el-form-item label="采购单位:">{{baseInfo.purchaseName}}</el-form-item>
						<el-form-item label="项目联系人姓名和电话:">{{baseInfo.consignee}}{{baseInfo.phone}}</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="供货地点:">{{baseInfo.requireAddress}}</el-form-item>
				<el-form-item label="项目描述:">{{baseInfo.projectRemark}}</el-form-item>
				<el-col v-if="baseInfo.projectState === '00026_5'">
					<el-form-item label="询价失败原因:">{{baseInfo.invalidRemark}}</el-form-item>
				</el-col>
				<el-form-item label="附件:">
					<template>
						<el-button type="text"
							@click="clickHandlePreview(baseInfo.entrustDocument)">{{baseInfo.entrustDocument|formatFile}}</el-button>
					</template>
				</el-form-item>
			</el-form>
			<h3 class="page-box-content-title">询价规则</h3>
			<el-form class="page-box-content-block form-space demo-form-inline" :inline="true"
				:label-position="labelPosition" label-suffix=":" label-width="160px" size="mini">
				<el-form-item :label="item.controlName" v-for="(item, index) in rulesInfo" :key="index"
					style="width: 50%">{{item.detailName}}
				</el-form-item>
			</el-form>
			<h3 class="page-box-content-title">上传保证金</h3>
			<el-table ref="bail" class="page-box-content-block" :data="purchaseList" style="width: 100%" border>
				<el-table-column label="项目金额" prop="sumPrice" min-width="120"></el-table-column>
				<el-table-column label="保证金金额" prop="pledgePrice" min-width="120"></el-table-column>
				<el-table-column label="审核状态" prop="auditStatusName" min-width="120"></el-table-column>
				<el-table-column label="审核原因" mix-width="140">
					<template slot-scope="scope" style="width: 100%">
						<el-popover placement="top" trigger="hover">
							<div class="cell-content">{{scope.row.auditOpinion}}</div>
							<p class="overflow" slot="reference">{{scope.row.auditOpinion}}</p>
						</el-popover>
					</template>
				</el-table-column>
			</el-table>
			<el-row>
				<el-form label-width="100px" label-suffix=":" :model="ruleForm" :rules="rules" ref="purchaseForm">
					<el-form-item label="上传凭证" prop="fileIds">
						<div v-if="Number(baseInfo.pledgePrice) <= 0">无需上传</div>
						<div v-else>
							<!--  未上传保证金/保证金审核退货  -->
							<el-upload
								v-if="isApply && (certificateIdInfo.auditStatus === 'FAIL' || rowData.uploadStatus ==='UNDO') "
								:action=fileUrl :data="{ fileType: 1}" :headers=fileHeaders multiple :limit="5"
								:file-list="fileList" :on-preview="handlePreview" :on-remove="handleRemove"
								:on-success="handleAvatarSuccess" :on-error="handleAvatarError"
								:before-upload="beforeAvatarUpload" :on-exceed="handleExceed">
								<el-button size="small" type="primary">上传附件</el-button>
								<div slot="tip" class="el-upload__tip" style="padding-top: 10px;">
									最多可以上传5张图片，每张图片大小不能超过5M,支持bmp,gif,png,jpeg格式文件</div>
							</el-upload>
							<!--  查看保证金资质 -->
							<div v-else>
								<el-button type="text" v-for="file in pledgeFiles" :key="file.id"
									@click="handlePreview(file)">{{file.name}}</el-button>
							</div>
						</div>
						<el-input v-model="ruleForm.fileIds" style="display: none"></el-input>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row v-if="isApply" style="text-align: center; padding: 40px 0;">
				<!--  uploadStatus: DO 已上传 UNDO未上传  -->
				<el-button v-if="rowData.uploadStatus ==='UNDO' " type="primary" @click="submitProject">项目报名</el-button>
				<el-button v-else-if="certificateIdInfo.auditStatus === 'FAIL'" type="primary"
					@click="editorProject">重新报名</el-button>
			</el-row>
		</div>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	// 导入工具函数
	import tools from '@/tools'
	import {
		queryDictionaryList,
		deleteFile,
		getFileUrl,
		getFileInfo,
		queryFileList
	} from '@/api/common.api'
	import {
		queryProOrderInfo,
		getBiddingRules,
		querySecondTime,
		postPurchaseProSuppliersCertificate,
		putPurchaseProSuppliersCertificate,
		getPurchaseDetailById
	} from '@/api/supplier.api'
	import moment from 'moment'
	import {
		beforeUpload
	} from '@/util/common'
	// 上传文件
	import fileUpdata from '@/api/file.config'
	export default {
		inject: ['reload'], //注入刷新依赖
		name: 'pro-editor',
		components: {},
		data() {
			return {
				// 附件
				fileUrl: '',
				fileHeaders: {},
				attactments: [],
				fileList: [],

				dialogVisible: false,
				dialogImageUrl: '',

				labelPosition: 'right',
				stateList: [],
				rowData: {},
				baseInfo: {},
				timer: '', // 定时器
				countdown: 0, // 倒计时
				strCountdown: '', //倒计时显示文字
				rulesInfo: [],
				purchaseList: [{
					sumPrice: '',
					pledgePrice: '',
					auditStatusName: '',
					auditOpinion: ''
				}], // 保证金数据
				pledgeFiles: [], // 保证金文件
				isApply: false, // 是否项目报名
				certificateIdInfo: {},
				ruleForm: {
					fileIds: ''
				},
				rules: {
					fileIds: [{
						required: true,
						message: '请上传保证金附件',
						trigger: 'change'
					}]
				},
				// 保证金额
				safeguardPrice: {},
				// 保证状态
				safeguardState: {}
			}
		},
		watch: {
			safeguardPrice(value) {
				for (let item in value) {
					this.purchaseList[0][item] = value[item]
				}
				this.$nextTick(() => {
					this.$refs.bail.doLayout()
				})
			},
			safeguardState(value) {
				for (let item in value) {
					this.purchaseList[0][item] = value[item]
				}
				this.$nextTick(() => {
					this.$refs.bail.doLayout()
				})
			}
		},
		computed: {},
		filters: {
			formeTime(val) {
				return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ' '
			},
			formatFile(value) {
				if (value !== null && value !== undefined && value) {
					const objItem = JSON.parse(value)
					return objItem.name
				} else {
					return ''
				}
			}
		},
		created() {
			// 查询项目状态
			this.queryProjectStatusListFn()
		},
		mounted() {
			this.rowData = JSON.parse(this.$route.query.data)
			this.isApply = this.rowData.isApply
			// 文件请求头
			this.fileHeaders = {
				...fileUpdata.headers()
			}
			this.fileUrl = fileUpdata.url
			this.$nextTick(() => {
				// 项目基本信息
				this.queryProOrderInfoFn()
				// 查询项目询价规则
				this.getBiddingRulesFn()
			})

		},
		methods: {
			// 查询指定主键的资质详情
			getPurchaseDetailByIdFn() {
				const self = this
				getPurchaseDetailById(this.rowData.certificateId).then(res => {
					self.certificateIdInfo = res
					this.safeguardState = {
						auditStatusName: res.auditStatusName,
						auditOpinion: res.auditOpinion
					}
					this.$forceUpdate()
					// 附件ID是否存在
					if (res.resourceId !== null && res.resourceId) {
						const arrIds = res.resourceId.split(',')
						const arrTemp = []
						queryFileList(1, {
								sourceIds: res.resourceId
							})
							.then(res => {
								res.forEach(item => {
									const fileInfo = {
										name: item.submittedFileName,
										url: item.url,
										id: item.id,
										fileType: item.fileType
									}
									arrTemp.push(fileInfo)
								})
								const arrSort = []
								for (let i = 0, max = arrIds.length; i < max; i++) {
									const objItem = arrIds[i]
									const curArr = arrTemp.filter(item => item.id === objItem)
									if (curArr.length > 0) {
										arrSort.push(curArr[0])
									}
								}
								this.pledgeFiles = arrSort
							})
							.catch(() => {
								this.pledgeFiles = []
							})
					} else {
						this.pledgeFiles = []
					}

				})
			},
			// 项目报名
			submitProject() {
				this.$refs.purchaseForm.validate((valid) => {
					if (valid) {
						const params = {
							fkProProjectsId: this.rowData.projectId,
							resourceId: this.attactments.length > 0 ? this.attactments.join(',') : ''
						}
						postPurchaseProSuppliersCertificate(params).then(res => {
							this.$message({
								message: '报名成功',
								type: 'success'
							})
							this.$router.go(-1)
						})
					}
				})
			},
			// 编辑项目
			editorProject() {
				this.$refs.purchaseForm.validate((valid) => {
					if (valid) {
						const params = {
							id: this.rowData.certificateId,
							resourceId: this.attactments.length > 0 ? this.attactments.join(',') : ''
						}
						putPurchaseProSuppliersCertificate(params).then(res => {
							this.$message({
								message: '编辑成功',
								type: 'success'
							})
							this.$router.go(-1)
						})
					}
				})
			},
			/**
			 * @description 查询项目状态
			 * @author 穆宏宇
			 * @date 2020-10-13 10:19:10
			 * @param
			 * @return
			 * */
			queryProjectStatusListFn() {
				const param = {
					dictionaryType: 'project_status'
				}
				queryDictionaryList(param).then(res => {
					this.stateList = res
				})
			},
			/**
			 * @description 查询项目距离报名时间
			 * @author 穆宏宇
			 * @date 2020-10-15 13:10:21
			 * @param
			 * @return
			 * */
			querySecondTimeFn() {
				const self = this
				querySecondTime({
					endTime: this.baseInfo.startTime
				}).then(res => {
					self.countdown = res
					self.timer = window.setInterval(() => {
						if (self.countdown >= 0) {
							self.countdownFn(self.countdown)
						} else {
							window.clearInterval(self.timer) //清除定时器
						}
					}, 1000)
				})
			},
			// 倒计时执行方法
			countdownFn(second) {
				this.countdown = this.countdown - 1
				this.strCountdown = tools.timeStamp(second)
			},
			/**
			 * @description 项目基本信息
			 * @author 穆宏宇
			 * @date 2020-10-14 14:46:35
			 * @param
			 * @return
			 * */
			queryProOrderInfoFn() {
				const self = this
				queryProOrderInfo(this.rowData.projectId).then(res => {
					self.baseInfo = res
					// 保证金额
					self.safeguardPrice = {
						sumPrice: res.sumPriceStr,
						pledgePrice: res.pledgePrice
					}
					// 项目倒计时 / 保证金 > 0
					if (res.projectState === '00026_0' && Number(res.pledgePrice) > 0 && this.isApply) {
						this.rules.fileIds[0].required = true
					} else {
						this.rules.fileIds[0].required = false
					}
					// 项目状态code转文字
					for (let item in this.stateList) {
						if (this.baseInfo.projectState === this.stateList[item].dictionaryKey1) {
							this.$set(this.baseInfo, 'projectStateName', this.stateList[item].optional1)
							break
						}
					}
					// 项目倒计时
					if (res.projectState === '00026_0') {
						// 查询项目距离报名时间
						this.querySecondTimeFn()
					}
					// 上传完保障金
					if (this.rowData.uploadStatus === 'DO') {
						// 查询指定主键的资质详情
						this.getPurchaseDetailByIdFn()
					}
				})
			},
			/**
			 * @description 查询项目询价规则
			 * @author 穆宏宇
			 * @date 2020-10-14 15:04:02
			 * @param
			 * @return
			 * */
			getBiddingRulesFn() {
				getBiddingRules(this.rowData.projectId).then(res => {
					this.rulesInfo = res
				})
			},
			// 预览附件
			clickHandlePreview(value) {
				if (value !== null && value !== undefined && value) {
					let objItem = ''
					if (value instanceof Object) {
						objItem = value
					} else {
						objItem = JSON.parse(value)
					}
					// 获取附件信息
					getFileInfo(objItem.fileType, objItem.id).then(res => {
						if (['image/png', 'image/jpeg'].includes(res.contextType)) {
							this.dialogImageUrl = res.url
							this.dialogVisible = true
						} else {
							// 下载
							document.location.href = res.url
						}
					})
				}
			},
			// 预览附件
			handlePreview(file) {
				getFileUrl(file.fileType, file.id).then(res => {
					this.dialogImageUrl = res
					this.dialogVisible = true
				})
			},
			// 删除附件
			handleRemove(file, fileList) {
				const self = this
				if (file && file.status === "success") {
					self.fileList = self.fileList.filter(item => item.id !== file.id)
					self.attactments = self.attactments.filter(item => item !== file.id)
					if (self.fileList.length === 0) {
						this.$set(this.ruleForm, 'fileIds', '')
						this.$forceUpdate()
					}
				}
			},
			handleExceed(files, fileList) {
				this.$message.warning(`最多可上传 5 个附件，您已超限`)
			},
			handleAvatarSuccess(res, file) {
				const curFile = {
					name: res.data.submittedFileName,
					url: res.data.url,
					id: res.data.id,
					fileType: res.data.fileType
				}
				this.fileList.push(curFile)
				this.attactments.push(res.data.id)
				if (this.fileList.length > 0) {
					this.$set(this.ruleForm, 'fileIds', 'default')
					this.$forceUpdate()
				}
			},
			handleAvatarError(res, file) {
				this.$message.error("文件上传失败，请重试")
			},
			beforeAvatarUpload(file) {
				//const isJPG = file.type === 'image/jpeg';
				const typeList = ['png', 'jpg', 'jpeg']
				const isJPG = beforeUpload(file, typeList)
				const isLt5M = file.size / 1024 / 1024 < 5
				if (!isJPG) {
					this.$message.error('上传文件格式不符合!')
				}
				if (!isLt5M) {
					this.$message.error('上传附件大小不能超过 5MB!')
				}
				return isJPG && isLt5M
			}
		},
		beforeDestroy() {
			if (this.timer) {
				window.clearInterval(this.timer) //清除定时器
			}
		}
	}
</script>

<style scoped lang="scss">
	.page-box {
		background: white;
		padding: 20px;

		&-content {
			padding: 20px;

			&-title {
				padding-top: 20px;
			}

			&-block {
				border-top: 3px solid #97a8be;
			}
		}
	}

	.form-space {
		padding: 20px;
	}

	.cell-content {
		width: 200px;
		min-height: 20px;
		max-height: 200px;
		overflow-y: auto;
	}

	.overflow {
		width: 100%;
		white-space: nowrap;
		text-overflow: ellipsis;
		-o-text-overflow: ellipsis;
		overflow: hidden;
	}

	/* 解决element-ui的table表格控件表头与内容列不对齐问题 */
	.el-table th.gutter {
		display: table-cell !important;
	}
</style>